# target_url.py 重构为函数形式

from datetime import datetime
import requests
import pandas as pd
import os
from comment.get_shuruxinxi import get_shuruxinxi
from comment.get_sanyaosu import get_sanyaosu
from compements.huoqvshenfenliebiao import fetch_and_save_appointment_data
from comment.cookie_find import get_cookies  # 注意：此处依赖修改后的cookie_find.py
from compements.yyys import get_yyys
from comment.get_date import generate_dates_by_rules


def process_admin(admin_path, n):
    """
    处理单个admin_n.txt的线程函数
    :param admin_path: admin_n.txt的路径（如./文档/admin_1.txt）
    :param n: 编号（如1、2...）
    """
    # 1. 动态生成输出文件路径
    env_file = f"执行结果/env_{n}.txt"
    output_xlsx = f"执行结果/复诊预约人员统计_{n}.xlsx"

    # 2. 创建输出目录（确保存在）
    os.makedirs("执行结果", exist_ok=True)

    # 3. 获取当前admin对应的cookies和URL
    url_ip, cookies,url2_ip, cookies2 = get_cookies(admin_path)  # 传入动态路径

    print(f"线程{n}：url_ip={url_ip}, cookies={cookies},url2_ip:{url2_ip},cookies2:{cookies2}")



    # 4. 上传页URL
    url = f"{url_ip}/cis/dwsreferralbookings/savedwsreferralbookings/"
    headers = {
        "Accept": "application/json",
        "Cookie": f"JSESSIONID={cookies}",
    }

    # 5. 获取三要素并抓取预约数据
    try:
        ysdm, ksdm, jigouma,ysmc = get_sanyaosu(url_ip, cookies)
    except Exception as e:
        with open(f"执行结果/错误信息{n}.txt", 'a', encoding='utf-8') as f:
            f.write(f"线程{n}获取三要素失败：{e}\n")
        print(f"线程{n}：获取三要素失败：{e}，重试或者联系管理员")
        return
    chenggonghuoqv_list = fetch_and_save_appointment_data(url_ip, cookies, ysdm, ksdm, jigouma, output_xlsx,n)
    if not chenggonghuoqv_list:
        with open(f"执行结果/错误信息{n}.txt", 'a', encoding='utf-8') as f:
            f.write(f"线程{n}：没有检测到可预约的挂号\n")

    # 6. 读取Excel并处理

    df = pd.read_excel(output_xlsx, dtype={'患者唯一标识符': str, '注册编号': str})
    if df.empty:
        with open(f"执行结果/错误信息{n}.txt", 'a', encoding='utf-8') as f:
            f.write("没有可预约的挂号")
        print(f"线程{n}：没有可预约的挂号")
        return

    # 7. 封装env文件写入函数（动态路径）
    def env_write(file_path, line_number, content):
        with open(file_path, 'r+', encoding='utf-8') as f:
            lines = f.readlines()
            if line_number <= len(lines):
                lines[line_number - 1] = content + '\n'
            else:
                lines.extend(['\n'] * (line_number - len(lines) - 1))
                lines.append(content + '\n')
            f.seek(0)
            f.writelines(lines)

    # 8. 初始化env文件（若不存在则创建）
    if not os.path.exists(env_file):
        with open(env_file, 'w', encoding='utf-8') as f:
            f.write("一共需要预约人数为:0\n已经预约了:0\n未成功人数:0\n已处理完:0\n")

    # 9. 写入总人数
    total = len(df)
    env_write(env_file, 1, f"一共需要预约人数为:{total}")

    # 10. 读取env参数（续跑逻辑）
    with open(env_file, 'r', encoding='utf-8') as f:
        sums = f.readlines()
        number = int(sums[1].strip().split(":")[-1]) if len(sums) >= 2 else 0
        e_num = int(sums[2].strip().split(":")[-1]) if len(sums) >= 3 else 0
        end_chuli = int(sums[3].strip().split(":")[-1]) if len(sums) >= 3 else 0



    with open(admin_path, 'r', encoding='utf-8') as f1:
        ad = f1.readlines()
        has_yyys = ad[4].strip().split(":")[-1]
        riqi_guize = ad[5]



    # 11. 遍历数据处理预约
    for index, row in df.iloc[end_chuli:].iterrows():
        name = row['姓名']
        patient_code = row['患者唯一标识符']
        reg_number = row['注册编号']
        Yyks = row['科室']
        yvyuehaobie = row['预约号别']
        print(f"线程{n}：处理患者{name}，参数{patient_code},{reg_number}")


        # 获取预约医生
        qyys = get_yyys(cookies2, url2_ip, name, jigouma)

        dates = generate_dates_by_rules(riqi_guize)
        # 提交预约请求
        for Yyrq in dates:
            data = get_shuruxinxi(url_ip, patient_code, reg_number, cookies, Yyks, yvyuehaobie, Yyrq,qyys,ysmc,ysdm,has_yyys)

            res = requests.post(url, headers=headers, json=data)
            print(f"线程{n}：状态码{res.status_code}，响应{res.text}")
            if res.text  not in ['0', '1']:
                data = get_shuruxinxi(url_ip, patient_code, reg_number, cookies, Yyks, yvyuehaobie, Yyrq, qyys, ysmc,
                                      ysdm,has_yyys)
                res = requests.post(url, headers=headers, json=data)
                print(f"线程{n}：状态码{res.status_code}，响应{res.text}")
                if res.text  not in ['0', '1']:
                    break
                else:
                    continue

        if res.text not in ['0', '1']:
            with open(f"执行结果/错误信息{n}.txt", 'a', encoding='utf-8') as f:
                f.write(f"{name}:预约失败\n")
            e_num+=1
            env_write(env_file, 3, f"未成功人数:{e_num}")
            end_chuli+=1
            env_write(env_file, 4, f"已处理完:{end_chuli}")
            continue

        # 更新已预约人数
        number += 1
        env_write(env_file, 2, f"已经预约了:{number}")
        end_chuli+=1
        env_write(env_file, 4, f"已处理完:{end_chuli}")

        print(f"线程{n}：已预约{number}/{total}")